<template>
  <div class="app-container" align="center" style="width: 1300px">
    <el-card class="box-card" align="center">
      <div slot="header" class="clearfix">
        <span>我的名片</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="showCardDialog()">修改</el-button>
      </div>
      <div align="center">
        <el-card class="friend-card" align="center" shadow="hover">
          <div class="block">
            <el-avatar :size="80" :src="user.avatar"></el-avatar>
          </div>
          <div style="padding: 14px;">
            <div class="text-nickName" :style="{marginBottom: '10px'}">{{ user.nickName }}</div>
            <div class="text-brief-long">{{ user.signature }}</div>
            <el-tag size="small" type="success" class="card-tag">{{ user.profession }}</el-tag>
            <el-tag size="small" v-if="user.gender = 1 " class="card-tag">男</el-tag>
            <el-tag size="small" v-if="user.gender = 0 " class="card-tag">女</el-tag>
            <div class="text-info">职业：{{ user.profession }}</div>
            <div class="text-info">生日：{{ user.birthday }}</div>
            <div class="text-info">手机：{{ user.phone }}</div>
            <div class="text-info">邮箱：{{ user.email }}</div>
          </div>
        </el-card>
      </div>
    </el-card>

    <el-dialog title="个人信息" :visible.sync="cardDialogVisible" width="858px" @close="closeDialog()">
      <!-- 内容主体 -->
      <div>
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item label="头像" prop="picture">
                <el-upload
                  ref="upload"
                  class="avatar-uploader"
                  action="http://127.0.0.1:8080/network/user/uploadImg"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  <div slot="tip" class="el-upload__tip">只能上传图片类型文件，且不超过2MB</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="formData.gender" size="medium">
                  <el-radio v-for="(item, index) in genderOptions" :key="index" :label="item.value"
                            :disabled="item.disabled">{{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item label="昵称" prop="nickName">
                <el-input v-model="formData.nickName" placeholder="请输入昵称" :maxlength="20" show-word-limit
                          clearable prefix-icon='el-icon-s-custom' :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item label="职业" prop="profession">
                <el-input v-model="formData.profession" placeholder="请输入职业" :maxlength="20" show-word-limit
                          clearable prefix-icon='el-icon-monitor' :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item label="所属省市：" prop="province">
                <el-select style="width: 50%" v-model="formData.province" placeholder="请选择省份（直辖市）" @change="renderCity" clearable>
                  <el-option
                    v-for="item in provinceListAll"
                    :key="item.name"
                    :value="item.name">
                  </el-option>
                </el-select>
                <el-select style="width: 50%" v-model="formData.city"  placeholder="请选择城市" v-if="citySelectAble" clearable>
                  <el-option
                    v-for="item in cityListAll"
                    :key="item.name"
                    :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker v-model="formData.birthday" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                :style="{width: '100%'}" placeholder="请选择生日" clearable></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item label="手机" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入手机号" :maxlength="11" show-word-limit clearable
                          prefix-icon='el-icon-mobile' :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱" :maxlength="30" show-word-limit
                          clearable prefix-icon='el-icon-folder' :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item label="个性签名" prop="signature">
                <el-input v-model="formData.signature" type="textarea" placeholder="请输入个性签名"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="top">
            <el-col :span="15">
              <el-form-item size="large">
                <el-button type="primary" @click="submitForm"> 提交</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-dialog>
  </div>

</template>
<script>
import {mapGetters} from "vuex";
import {getInfo} from '@/api/user'
import request from "@/utils/request";
import store from "@/store";
export default {
  computed: {
    ...mapGetters([
      'name',
      'id',
      'user'
    ])
  },
  components: {},
  props: [],

  data() {
    return {
      userInfo: {},
      cardDialogVisible: false,
      imageUrl: '',
      avatar: '',
      formData: {
        nickName: '',
        profession: '',
        province: '',  // 所属省（直辖市）
        city: '',
        gender: 1,
        birthday: null,
        phone: '',
        email: '',
        signature: '',
        submit: '',
        reset: '',
      },
      mapApiKey: 'dc29f1c38025b144fd39e742bb45bb0b',
      provinceListAll: [],      // 全国34个省份（包括直辖市）列表
      cityListAll: [],        // 全国各个城市列表
      citySelectAble: false,    // 城市是否可选
      rules: {
        nickName: [{
          required: true,
          message: '请输入昵称',
          trigger: 'blur'
        }],
        profession: [{
          required: true,
          message: '请输入职业',
          trigger: 'blur'
        }],
        province:[{
          required: true,
          message: '请输入所属省份（或者直辖市）',
          trigger: 'blur'
        }],
        gender: [{
          required: true,
          message: '性别不能为空',
          trigger: 'change'
        }],
        birthday: [{
          required: true,
          message: '请选择生日',
          trigger: 'change'
        }],
        phone: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }],
        signature: [{
          required: true,
          message: '请输入个性签名',
          trigger: 'blur'
        }],
      },
      genderOptions: [{
        "label": "男",
        "value": 1
      }, {
        "label": "女",
        "value": 0
      }],
    }
  },
  watch: {},
  created() {
    this.getAllProvinceAndCityList();
  },
  mounted() {
  },
  methods: {

    getAllProvinceAndCityList() {     // 获取全国所有省份和城市的列表
      var that = this;
      this.$http.get('https://restapi.amap.com/v3/config/district',{   // 高德地图的API
        params:{
          key: this.mapApiKey,   // 这个是申请的 Key
          keywords: '中国',
          subdistrict: 3,
          extensions: 'base'
        }
      }).then((response) => {
        that.provinceListAll = response.data.districts[0].districts;
        for (let i = 0; i < response.data.districts[0].districts.length; i++) {
          for (let j = 0; j < response.data.districts[0].districts[i].districts.length; j++) {
            that.cityListAll.push(response.data.districts[0].districts[i].districts[j]);
          }
        }
        // console.log('省份',that.provinceListAll);
        // console.log('城市',that.cityListAll);
      });
    },

    renderCity() {    // 根据选择的省份，展示该省份相对应的城市列表，未选择省份时，不能选择城市
      this.citySelectAble = false;
      if((this.formData.province.length > 0) && (this.formData.city)){
        this.formData.city = '';
      }
      if(this.formData.province.length > 0) {
        this.cityListAll = this.provinceListAll.filter(item => item.name == this.formData.province)[0].districts;
        this.citySelectAble = true;
      } else if(!this.formData.province) {
        this.citySelectAble = false;
        this.formData.city = '';     // 清空省份选择时，清空之前选择的城市能进行重新选择城市
      }
    },

    // 显示对话框
    showCardDialog() {

      getInfo(this.user.id).then(response => {
        this.formData = response.data
        this.imageUrl = response.data.avatar
        console.log(response.data)
      })
      this.cardDialogVisible = true
    },
    closeDialog() {
      this.formData={}
      this.cardDialogVisible = false
    },
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        const params = this.formData
        if (this.avatar) {
          params.avatar = this.avatar
        }
        request({
          url: '/user/updateUser',
          method: 'get',
          params
        }).then(response => {
          console.log("发送请求")
          console.log(response.retCode)
          if (response.retCode !== '200') return this.$message.error(response.retMsg)
          this.$message.success('发送请求成功！')
          this.$refs['elForm'].resetFields()
          this.cardDialogVisible = false
          location.reload();
        })
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },


    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.avatar = res;
    },
    beforeAvatarUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('image/*').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择图片类型的文件')
      }
      return isRightSize && isAccept

    }
  }
}

</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 1000px;
  margin-left: 80px;
}
</style>
